<?php
// +----------------------------------------------------------------------
// | likeadmin快速开发前后端分离管理后台（PHP版）
// +----------------------------------------------------------------------
// | 欢迎阅读学习系统程序代码，建议反馈是我们前进的动力
// | 开源版本可自由商用，可去除界面版权logo
// | gitee下载：https://gitee.com/likeshop_gitee/likeadmin
// | github下载：https://github.com/likeshop-github/likeadmin
// | 访问官网：https://www.likeadmin.cn
// | likeadmin团队 版权所有 拥有最终解释权
// +----------------------------------------------------------------------
// | author: likeadminTeam
// +----------------------------------------------------------------------

namespace app\adminapi\logic\return_rule;


use app\common\model\promotion\PromotionLink;
use app\common\model\return_rule\ReturnRule;
use app\common\logic\BaseLogic;
use app\common\model\return_rule\ReturnRuleDetail;
use think\facade\Db;


/**
 * ReturnRule逻辑
 * Class ReturnRuleLogic
 * @package app\adminapi\logic
 */
class ReturnRuleLogic extends BaseLogic
{


    /**
     * @notes 添加
     * @param array $params
     * @return bool
     * @author likeadmin
     * @date 2024/03/06 10:32
     */
    public static function add(array $params): bool
    {
        Db::startTrans();
        try {
            $promotion_link_id_arr = explode(',', $params['promotion_link_ids']);
            $detail                = json_decode($params['detail'], true);
            foreach ($promotion_link_id_arr as $k => $v) {
                $promotion = PromotionLink::where('id', $v)->find();
                if (!$promotion) {
                    self::setError('推广链接不存在');
                    return false;
                }
                $returnRule = ReturnRule::where('promotion_link_id', $v)->find();
                if ($returnRule) {
                    self::setError('推广链ID： ' . $v . '已存在回传规则');
                    return false;
                }
                if ($params['active'] == 0 && $params['add_desktop'] == 0) {
                    self::setError('上报行为激活和加桌必须选择一个');
                    return false;
                }
                $data                      = [];
                $data['promotion_link_id'] = $v;
                $data['admin_id']          = $params['admin_id'];
                $data['app_id']            = $params['app_id'];
                $data['name']              = $promotion['name'];
                $data['date_pattern']      = $params['date_pattern'];
                $data['type']              = $params['type'];
                $data['active']            = $params['active'];
                $data['add_desktop']       = $params['add_desktop'];
                $data['register']          = $params['register'];
                $data['activity_order']    = $params['activity_order'];
                $data['key_behaviors']     = $params['key_behaviors'];
                $data['time']              = strtotime($params['time']);
                $data['day']               = $params['day'] ?? 0;
                $data['hour']              = $params['hour'] ?? 0;
                $data['additional_hour']   = $params['additional_hour'] ?? 0;
                $data['additional_price']  = $params['additional_price'] ?? '';
                $data['additional_num']    = $params['additional_num'] ?? 0;
                $result                    = ReturnRule::create($data);
                foreach ($detail as $key => $value) {
                    $detail_data                   = [];
                    $detail_data['return_rule_id'] = $result->id;
                    $detail_data['min_price']      = $value['min_price'];
                    $detail_data['max_price']      = $value['max_price'];
                    $detail_data['return_type']    = $value['return_type'];
                    if ($value['return_type'] == 3) {
                        $detail_data['reported_num'] = $value['reported_num'];
                        $detail_data['missed_num']   = $value['missed_num'];
                    }
                    ReturnRuleDetail::create($detail_data);
                }
            }


            Db::commit();
            return true;
        } catch (\Exception $e) {
            Db::rollback();
            self::setError($e->getMessage());
            return false;
        }
    }


    /**
     * @notes 编辑
     * @param array $params
     * @return bool
     * @author likeadmin
     * @date 2024/03/06 10:32
     */
    public static function edit(array $params): bool
    {
        Db::startTrans();
        try {
            if ($params['active'] == 0 && $params['add_desktop'] == 0) {
                self::setError('上报行为激活和加桌必须选择一个');
                return false;
            }
            $detail                   = json_decode($params['detail'], true);
            $data                     = [];
            $data['date_pattern']     = $params['date_pattern'];
            $data['type']             = $params['type'];
            $data['active']           = $params['active'];
            $data['add_desktop']      = $params['add_desktop'];
            $data['register']         = $params['register'];
            $data['activity_order']   = $params['activity_order'];
            $data['key_behaviors']    = $params['key_behaviors'];
            $data['time']             = strtotime($params['time']);
            $data['day']              = $params['day'] ?? 0;
            $data['hour']             = $params['hour'] ?? 0;
            $data['additional_hour']  = $params['additional_hour'] ?? 0;
            $data['additional_price'] = $params['additional_price'] ?? '';
            $data['additional_num']   = $params['additional_num'] ?? 0;
            ReturnRule::where('id', $params['id'])->update($data);
            ReturnRuleDetail::where('return_rule_id', $params['id'])->delete();
            foreach ($detail as $key => $value) {
                $detail_data                   = [];
                $detail_data['return_rule_id'] = $params['id'];
                $detail_data['min_price']      = $value['min_price'];
                $detail_data['max_price']      = $value['max_price'];
                $detail_data['return_type']    = $value['return_type'];
                if ($value['return_type'] == 3) {
                    $detail_data['reported_num'] = $value['reported_num'];
                    $detail_data['missed_num']   = $value['missed_num'];
                }
                ReturnRuleDetail::create($detail_data);
            }
            Db::commit();
            return true;
        } catch (\Exception $e) {
            Db::rollback();
            self::setError($e->getMessage());
            return false;
        }
    }


    /**
     * @notes 删除
     * @param array $params
     * @return bool
     * @author likeadmin
     * @date 2024/03/06 10:32
     */
    public static function delete(array $params): bool
    {
        return ReturnRule::destroy($params['id']);
    }


    /**
     * @notes 获取详情
     * @param $params
     * @return array
     * @author likeadmin
     * @date 2024/03/06 10:32
     */
    public static function detail($params): array
    {
        $result = ReturnRule::findOrEmpty($params['id'])->toArray();
        if ($result) {
            $result['detail'] = ReturnRuleDetail::where('return_rule_id', $result['id'])->select()->toArray();
        }
        return $result;
    }


    /**
     * @notes  更改状态
     * @param array $params
     * @return bool
     * @author heshihu
     * @date 2022/2/21 18:04
     */
    public static function updateStatus(array $params)
    {

        $rule = ReturnRule::where('id', $params['id'])->findOrEmpty();
        if ($rule->isEmpty()) {

            return false;
        }

        $rule->status = $params['status'] ?? 0;

        return $rule->save();
    }
}
